//
//  ShopCarViewController.m
//  体育商城
//
//  Created by  on 2022/9/24.
//

#import "ShopCarViewController.h"
#import "FavoriteCell.h"
#import "PayViewController.h"

@interface ShopCarViewController ()
@property (strong, nonatomic) IBOutlet UIButton *allSelectBtn;
@property (strong, nonatomic) IBOutlet UIView *toolbar;
@property (strong, nonatomic) IBOutlet UIButton *deleteBtn;
@property (strong, nonatomic) IBOutlet UILabel *allNum;
@property (strong, nonatomic) IBOutlet UILabel *totalMoney;
@property (strong, nonatomic)  NSMutableArray<Goods *> *array;
@end

@implementation ShopCarViewController

-  (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self initUI];
}

- (void)initUI{
    [self.navigationItem setTitle:[NSString stringWithFormat:LS(@"购物车(%d)"),(int)self.array.count]];


    self.backBtn.hidden = YES;
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[FavoriteCell nib] forCellReuseIdentifier:[FavoriteCell ID]];
    NSLayoutConstraint *top = [self.tableView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeTop c: 15];
    NSLayoutConstraint *left = [self.tableView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:15];
    NSLayoutConstraint *right = [self.tableView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:-15];
    NSLayoutConstraint *bottom = [self.tableView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.toolbar a2:NSLayoutAttributeTop c:0];
    [self.view addConstraints:@[top,left,right,bottom]];
}
- (void)loadData{
    [GoodsTool find:GoodsOrderStastusJoinCart complete:^(NSArray<Goods *> * _Nonnull result) {
        self.array = [NSMutableArray arrayWithArray:result];
    }];
}
- (void)setArray:(NSMutableArray<Goods *> *)array{
    _array = array;
    [self updateData:NO index:self.array.count + 1];
}
- (void)updateData:(BOOL)selected index:(NSInteger)index{
    int num = 0;
    CGFloat totalprivce = 0;
    for (int i = 0; i<self.array.count; i++) {
        Goods *model = self.array[i];
        if (self.array.count < index) {
            model.select = selected;
        }else{
            if (i == index && selected) { model.select = !model.select;}
        }
        num = model.select ? num+1:num;
        totalprivce = !model.select ? totalprivce : totalprivce + [model.price floatValue] * [model.payNum intValue];
    }
    if (self.array.count > index) {
        self.allSelectBtn.selected = self.array.count == num || (num > 0 && self.allSelectBtn.selected);
    }
    self.allNum.text = [NSString stringWithFormat:LS(@"已选%d件"),num];
    self.totalMoney.text = [NSString stringWithFormat:LS(@"¥:%0.1f"),totalprivce];
    [self.navigationItem setTitle:[NSString stringWithFormat:LS(@"购物车(%d)"),(int)self.array.count]];

    [self.tableView reloadData];
}

- (IBAction)actionForBtn:(UIButton *)sender {
    if (APP.user.account ==  nil || APP.user.account.length <= 0) {
        return [Toast msg:LS(@"您还未登录，请先去登录")];
    }
    if (sender.tag == 201) {///全选
        sender.selected = !sender.selected;
        [self updateData:sender.selected index:self.array.count+1];
    }else if (sender.tag == 202){///结算
        [Toast startHud:LS(@"结算中")];
        NSMutableArray *array = [NSMutableArray array];
        for (Goods *m in self.array) {
            if (m.select == NO) {
                [array addObject:m];
            }else{
                [GoodsTool delete:m complete:^{
                    m.orderStatus = GoodsOrderStastusPayed;
                    m.orderID = [NSDate currentTimeStamp:@"yyyy/MM/dd HH:mm:ss"];
                    [m bg_saveOrUpdateAsync:^(BOOL isSuccess) {
                    }];
                }];
                PayViewController *vc = [PayViewController new];
                [self.navigationController pushViewController:vc animated:NO];
            }
        }
        if (array.count == self.array.count) {
            [Toast startHud:LS(@"至少选择一件商品") stopTime:1 handle:nil];
        }
        self.array = array;
    }
}
- (void)actionForCellBtn:(UIButton *)sender model:(BuyGoodModel*)model{
    if (sender.tag == 201){///选中状态
        int num = 0;
        for (BuyGoodModel * m in self.array){
            if (m.select){
                num += 1;
            }
        }
        self.allSelectBtn.selected = num != 0;
        self.allNum.text = [NSString stringWithFormat:LS(@"已选%d件"),(int)self.array.count];
    }else if (sender.tag == 202) {///商店
        
    }
    [self.tableView reloadData];
}
- (void)addNotify{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:notifyJoinCartUpdate object:nil];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FavoriteCell *cell = [tableView dequeueReusableCellWithIdentifier:[FavoriteCell ID]];
    WS(self)
    cell.selectBtnLeft.constant = 10;
    cell.model = self.array[indexPath.section];
    cell.block = ^(UIButton * _Nonnull button) {
        [weakself updateData:button.tag == 201 index:indexPath.section];
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return section == self.array.count - 1 ? 20 : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == self.array.count - 1){
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor clearColor];
        return view;
    }else{
        return nil;
    }
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(self)
    if (@available(iOS 13,*)) {
        UIContextualAction *delete = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:LS(@"删除") handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            Goods *model = weakself.array[indexPath.section];
            [GoodsTool delete:model complete:nil];
            [weakself.array removeObjectAtIndex:indexPath.section];
            [tableView reloadData];
        }];
        delete.backgroundColor = [UIColor colorHex:@"#F22E1C"];
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[delete]];
        return config;
    }
    return nil;
}
@end
